import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { TreeRepository, UpdateResult } from 'typeorm';
import { AssetEntity } from '../entities/asset.entity';
import { MysqlBaseService } from './mysql-base.service';
import { CreateAssetDto, UpdateAssetDto } from '../dtos/asset.dto';
import { Result } from '../vo/result';

@Injectable()
export class AssetService extends MysqlBaseService<AssetEntity> {
  constructor(
    @InjectRepository(AssetEntity)
    protected repository: TreeRepository<AssetEntity>,
  ) {
    super(repository);
  }

  async findAll() {
    const assetTrees = await this.repository.findTrees({
      relations: ['parent', 'children'],
    });
    return assetTrees.filter((asset) => !asset.parent);
  }
  async create(createDto: CreateAssetDto) {
    const { parentId, ...dto } = createDto;
    const asset = this.repository.create(dto); //创一个抽象实体
    if (parentId) {
      //判断是否有parentId，有则给asset设置父类
      asset.parent = await this.repository.findOneBy({ id: parentId });
    }
    // 返回保存
    return await this.repository.save(asset);
  }
  // 更新
  async update(id: number, updateDto: UpdateAssetDto) {
    const { parentId, ...dto } = updateDto;
    const asset = await this.repository.findOneBy({ id });
    if (!asset) {
      throw new HttpException('未找到', HttpStatus.NOT_FOUND);
    }
    Object.assign(asset, dto);
    if (parentId) {
      asset.parent = await this.repository.findOneBy({ id: parentId });
    }
    await this.repository.save(asset);
    const result = UpdateResult.from({ raw: [], affected: 1, records: [] });
    if (result.affected) {
      return Result.success('用户更新成功');
    } else {
      throw new HttpException('用户未更新成功', HttpStatus.NOT_FOUND);
    }
  }
}
